<template>
  <div>
    <el-dialog
      title="编辑用户"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
    >
      <el-form
        :rules="rules"
        :model="editUserForm"
        ref="editUserFormRef"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="20">
            <div class="grid-content bg-purple">
              <el-form-item label="用户名" prop="username">
                <el-input v-model="editUserForm.username" disabled></el-input>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="20">
            <div class="grid-content bg-purple">
              <el-form-item label="姓名" prop="name">
                <el-input v-model="editUserForm.name"></el-input>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="20">
            <div class="grid-content bg-purple">
              <el-form-item label="电话" prop="mobile">
                <el-input v-model="editUserForm.mobile"></el-input>
              </el-form-item>
            </div>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="success" @click="submitForm('editUserForm')"
            >保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { updateUser } from 'api/userlist'
export default {
  name: 'EditUser',
  // 父组件传参
  props: ['rowdata'],
  data () {
    return {
      dialogVisible: false,
      rules: {
        username: [
          { required: true, message: '用户名不能为空', trigger: 'blur' },
          {
            min: 3,
            max: 20,
            message: '长度在 3 到 20 个字符',
            trigger: 'change'
          }
        ],
        name: [{ required: true, message: '姓名不能为空', trigger: 'change' }],
        mobile: [{ required: true, message: '手机不能为空', trigger: 'change' }]
      }
    }
  },
  // 计算属性初始化data中的editUserForm
  computed: {
    editUserForm: function () {
      return this.rowdata
    }
  },
  methods: {
    submitForm () {
      updateUser(this.editUserForm)
        .then(res => this.updateUserSuccess(res))
        .catch(err => console.log(err))
    },
    updateUserSuccess (res) {
      if (res.data.code === 0) {
        this.$message.success('更新成功！')
        this.dialogVisible = false
        this.$emit('getUserList')
      }
    },
    // 再次确认关闭方法
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },
    // 重置方法
    resetForm () {
      this.$refs.addUserFormRef.resetFields()
    }
  }
}
</script>
